﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net.Http;
using System.Text;
using YSC_Core.BLL.Domain.CommonModels;
using YSC_Core.BLL.Domain.Entity;
using YSC_Core.BLL.Domain.Models;
using YSC_Core.BLL.Domain.Utils;
using YSC_Core.BLL.Domain.ViewModels;
using YSC_Core.BLL.Repository;
using YSC_OpenPlatform_API.Entity;
using YSC_Services.BLL.Services.Interfaces;

namespace YSC_Services.BLL.Services.Implementations
{
    /// <summary>
    /// 用户接口
    /// </summary>
    public class UserAppServices : IUserAppServices
    {
        private IEfRepository _rep;

        public UserAppServices(IEfRepository rep)
        {
            this._rep = rep;
        }

        public YscUser OAuthUser(string userName, string passWord)
        {
            var item = _rep.FirstOrDefault<YscUser>(p => p.Phone == userName && p.Password == passWord);
            return item;
        }

        /// <summary>
        /// 账户密码登陆
        /// </summary>
        /// <param name="userName">手机号</param>
        /// <param name="passWord">密码</param>
        /// <returns></returns>
        public ReturnValueModel Login(string userName, string passWord)
        {

            try
            {
                var userItem = _rep.FirstOrDefault<YscUser>(p => p.Phone == userName && p.Password == UtilsHelp.GetMD5(passWord));
                //http://yscoauth.cnfm.com.cn:8033/connect/token

                string TokenUrl = "http://yscoauth.cnfm.com.cn:8099/connect/token";
                // string TokenUrl = "http://localhost:5000/connect/token";
                string dateStr = string.Format("username={0}&password={1}&client_id=ro.client&client_secret=secret&grant_type=password", userName, passWord);
                Dictionary<string, string> postData = new Dictionary<string, string>();

                postData.Add("userName", userName);
                postData.Add("password", UtilsHelp.GetMD5(passWord));
                postData.Add("client_id", "ro.client");
                postData.Add("client_secret", "secret");
                postData.Add("grant_type", "password");

                // 自己实现的http请求
                string postStr = HttpUtils.DictoryToGetParam(postData);
                var repose = HttpUtils.HttpPostRequest(TokenUrl, postStr);
                if (repose.Contains("400"))
                    return new ReturnValueModel { Code = 400, Msg = "账户密码错误!", Result = repose };

                TokenModel tokenModel = JsonConvert.DeserializeObject<TokenModel>(repose);
                tokenModel.UserName = System.Web.HttpUtility.UrlDecode(userItem.UserName, System.Text.Encoding.UTF8);
                tokenModel.IsAttest = userItem.IsAttest;
                tokenModel.UserHeadPortraitUrl = userItem.HeadPortraitImageUrl;

                if (userItem.IsAttest == true && string.IsNullOrEmpty(userItem.AttestType))
                    return new ReturnValueModel { Code = 500, Msg = "用户权限丢失!" };
                if (userItem.IsAttest == true)
                    tokenModel.AttestName = _rep.FirstOrDefault<Dictionary>(p => p.Id == userItem.AttestType).Name;

                return new ReturnValueModel { Code = 200, Msg = "success!", Result = tokenModel };
            }
            catch (Exception e)
            {
                return new ReturnValueModel { Code = 500, Msg = "授权出现错误!", Result = e };
            }

        }


        /// <summary>
        /// 微信登陆
        /// </summary>
        /// <param name="openid"></param>
        /// <returns></returns>
        public ReturnValueModel WxLogin(string openid)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public YscUser OAuthUserId(string userid)
        {
            var item = _rep.FirstOrDefault<YscUser>(p => p.Id == userid);
            return item;
        }

        /// <summary>
        /// 短信验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public ReturnValueModel SMSCode(string phone)
        {

            var ret = SendShort.SignDemo(phone, "测试数据", "张家界综合应用平台", "name", "SMS_180785216");
            if (!string.IsNullOrEmpty(ret))
                return new ReturnValueModel { Code = 200, Msg = "success!", Result = ret };

            int msmCode;
            var msmItem = string.Empty; ;
            var msmAll = _rep.Where<MSM>(p => p.Status == 0 && p.phone == phone && (DateTime.Now - p.CreateTime).Minutes <= 15).ToList();
            if (msmAll.Count() == 0)
            {
                MSM item = new MSM()
                {
                    Id = Guid.NewGuid().ToString(),
                    phone = phone,
                    VerificationCode = UtilsHelp.GetRandNumInt(),
                    ExpireDate = UtilsHelp.GetTimeStamp(),
                    Status = 0,
                    CreateTime = DateTime.Now,
                    CreateId = "4076e59b-c219-11e9-a7b7-48d53943449f"
                };
                _rep.Insert(item);
                msmItem = SendShort.SignDemo(phone, item.VerificationCode.ToString());
                return new ReturnValueModel { Code = 200, Msg = "success!", Result = msmItem };
            }
            var code = msmAll.FirstOrDefault().VerificationCode;

            // msmCode = UtilsHelp.GetRandNumInt();
            msmItem = SendShort.SignDemo(phone, code.ToString());
            return new ReturnValueModel { Code = 200, Msg = "success!", Result = msmItem };
        }

        /// <summary>
        /// 短信登陆
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="smsCode"></param>
        /// <returns></returns>
        public ReturnValueModel SMSLogin(string phone, string smsCode)
        {

            var msmAll = _rep.Where<MSM>(p => p.Status == 0 && p.phone == phone && (DateTime.Now - p.CreateTime).Minutes <= 15).ToList();

            var erfgf = (DateTime.Now - msmAll.FirstOrDefault().CreateTime).Minutes;
            if (msmAll.Count() == 0)
                return new ReturnValueModel { Code = 400, Msg = "验证码已过期,请重新发送验证码!", };

            if (msmAll.FirstOrDefault().VerificationCode.ToString() != smsCode)
                return new ReturnValueModel { Code = 400, Msg = "验证码错误,请重新发送验证码!", };

            string TokenUrl = "http://yscoauth.cnfm.com.cn:8099/connect/token";
            //string TokenUrl = "http://localhost:5000/connect/token";
            Dictionary<string, string> postData = new Dictionary<string, string>();

            var userItem = _rep.FirstOrDefault<YscUser>(p => p.Phone == phone);
            if (userItem != null)
            {
                postData.Add("userName", phone);
                postData.Add("password", userItem.Password);
                postData.Add("client_id", "ro.client");
                postData.Add("client_secret", "secret");
                postData.Add("grant_type", "password");

                // 自己实现的http请求
                string postStr = HttpUtils.DictoryToGetParam(postData);
                var repose = HttpUtils.HttpPostRequest(TokenUrl, postStr);
                if (repose.Contains("400"))
                    return new ReturnValueModel { Code = 400, Msg = "请求错误!", Result = repose };
                TokenModel tokenModel = JsonConvert.DeserializeObject<TokenModel>(repose);
                tokenModel.UserName = System.Web.HttpUtility.UrlDecode(userItem.UserName, System.Text.Encoding.UTF8);
                tokenModel.IsAttest = userItem.IsAttest;
                tokenModel.UserHeadPortraitUrl = userItem.HeadPortraitImageUrl;

                var msmlists = _rep.Where<MSM>(p => p.phone == phone && (DateTime.Now - p.CreateTime).Minutes > 15).ToList();
                if (msmlists.Count() > 0)
                    _rep.RemoveRange(msmlists);
                return new ReturnValueModel { Code = 200, Msg = "success!", Result = tokenModel };
            }


            YscUser yscUser = new YscUser()
            {
                Id = Guid.NewGuid().ToString(),
                UserName = phone,
                Password = UtilsHelp.GetMD5("123456"),
                Phone = phone,
                Age = DateTime.Now,
                AreaUnCode = "802",
                Sex = 0,
                IsAttest = false,
                Status = 0,
                CreateTime = DateTime.Now,
                CreateId = "4076e59b-c219-11e9-a7b7-48d53943449f",
            };
            _rep.Insert(yscUser);

            postData.Add("userName", yscUser.Phone);
            postData.Add("password", yscUser.Password);
            postData.Add("client_id", "ro.client");
            postData.Add("client_secret", "secret");
            postData.Add("grant_type", "password");

            // 自己实现的http请求
            string postStrs = HttpUtils.DictoryToGetParam(postData);
            var reposes = HttpUtils.HttpPostRequest(TokenUrl, postStrs);
            if (reposes.Contains("400"))
                return new ReturnValueModel { Code = 400, Msg = "请求错误!", Result = reposes };
            TokenModel tokenModels = JsonConvert.DeserializeObject<TokenModel>(reposes);
            tokenModels.UserName = System.Web.HttpUtility.UrlDecode(userItem.UserName, System.Text.Encoding.UTF8);
            tokenModels.IsAttest = userItem.IsAttest;
            tokenModels.UserHeadPortraitUrl = userItem.HeadPortraitImageUrl;
            if (userItem.IsAttest == true && string.IsNullOrEmpty(userItem.AttestType))
                return new ReturnValueModel { Code = 500, Msg = "用户权限丢失!" };
            if (userItem.IsAttest == true)
                tokenModels.AttestName = _rep.FirstOrDefault<Dictionary>(p => p.Id == userItem.AttestType).Name;

            var msmlist = _rep.Where<MSM>(p => p.phone == phone && (DateTime.Now - p.CreateTime).Minutes > 15).ToList();
            if (msmlist.Count() > 0)
                _rep.RemoveRange(msmlist);
            return new ReturnValueModel { Code = 200, Msg = "success!", Result = tokenModels };
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnValueModel Registered(RegisteredModel model)
        {
            var item = _rep.FirstOrDefault<YscUser>(p => p.Phone == model.Phone);
            if (item != null)
                return new ReturnValueModel { Code = 400, Msg = "您已注册，请前往登陆!", };

            var msmAll = _rep.Where<MSM>(p => p.Status == 0 && p.phone == model.Phone && (DateTime.Now - p.CreateTime).Minutes <= 15).ToList();
            if (msmAll.Count() == 0)
                return new ReturnValueModel { Code = 400, Msg = "验证码已过期,请重新发送验证码!", };

            if (msmAll.FirstOrDefault().VerificationCode.ToString() != model.SMSCode)
                return new ReturnValueModel { Code = 400, Msg = "验证码错误,请重新发送验证码!", };


            YscUser yscUser = new YscUser()
            {
                Id = Guid.NewGuid().ToString(),
                UserName = model.UserName,
                Password = string.IsNullOrEmpty(model.PassWord) ? UtilsHelp.GetMD5("123456") : UtilsHelp.GetMD5(model.PassWord),
                Phone = model.Phone,
                // HeadPortraitUrl = model.HeadPortraitUrl,
                Age = DateTime.Now,
                AreaUnCode = "802",
                Sex = 0,
                IsAttest = false,
                Status = 0,
                CreateTime = DateTime.Now,
                CreateId = "4076e59b-c219-11e9-a7b7-48d53943449f",
            };
            _rep.Insert(yscUser);

            string TokenUrl = "http://yscoauth.cnfm.com.cn:8099/connect/token";
            //string TokenUrl = "http://localhost:5000/connect/token";
            Dictionary<string, string> postData = new Dictionary<string, string>();
            postData.Add("userName", yscUser.Phone);
            postData.Add("password", yscUser.Password);
            postData.Add("client_id", "ro.client");
            postData.Add("client_secret", "secret");
            postData.Add("grant_type", "password");

            // 自己实现的http请求
            string postStrs = HttpUtils.DictoryToGetParam(postData);
            var reposes = HttpUtils.HttpPostRequest(TokenUrl, postStrs);
            if (reposes.Contains("400"))
                return new ReturnValueModel { Code = 400, Msg = "请求错误!", Result = reposes };
            TokenModel tokenModels = JsonConvert.DeserializeObject<TokenModel>(reposes);
            tokenModels.UserName = System.Web.HttpUtility.UrlDecode(yscUser.UserName, System.Text.Encoding.UTF8);
            //tokenModels.UserHeadPortraitUrl = yscUser.HeadPortraitImageUrl;
            // tokenModels.IsAttest = yscUser.IsAttest;

            var msmlist = _rep.Where<MSM>(p => p.phone == model.Phone && (DateTime.Now - p.CreateTime).Minutes > 15).ToList();
            if (msmlist.Count() > 0)
                _rep.RemoveRange(msmlist);
            return new ReturnValueModel { Code = 200, Msg = "success!", Result = tokenModels };
        }

        /// <summary>
        /// 用户详情
        /// </summary>
        /// <returns></returns>
        public ReturnValueModel GetUser(string userId)
        {
            if (string.IsNullOrEmpty(userId))
                return new ReturnValueModel { Code = 401, Msg = "临时凭证已过期!" };

            var dictionaryAll = _rep.Where<Dictionary>(p => true).ToList();

            var item = from a in _rep.Where<YscUser>(p => p.Id == userId)
                       join r in _rep.Where<Area>(p => true) on a.AreaUnCode equals r.YunCode
                       select new YscUserModel
                       {
                           Id = a.Id,
                           Remarks = a.Remarks,
                           Status = a.Status,
                           CreateTime = a.CreateTime,
                           UserName = System.Web.HttpUtility.UrlDecode(a.UserName, System.Text.Encoding.UTF8),
                           Phone = a.Phone,
                           Sex = a.Sex,
                           Age = a.Age,
                           AreaUnCode = a.AreaUnCode,
                           AreaName = r.AreaName,
                           HeadPortraitUrl = a.HeadPortraitImageUrl,
                           Background = string.IsNullOrEmpty(a.Background) ? a.Background : string.Format("https://fishopeni.cnfm.com.cn:8095" + a.Background),
                           IsAttest = a.IsAttest,
                           Introduce = a.Introduce,
                           AttestType = string.IsNullOrEmpty(a.AttestType) ? a.AttestType : dictionaryAll.FirstOrDefault(p => p.Id == a.AttestType).Name
                       };


            var models = item.ToList();

            if (models.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "该用户状态异常!" };

            return new ReturnValueModel { Code = 200, Msg = "success!", Result = models };
        }

        /// <summary>
        /// 用户基本信息修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnValueModel UpdateUser(YscUserModel model)
        {
            if (string.IsNullOrEmpty(model.Id))
                return new ReturnValueModel { Code = 401, Msg = "临时凭证已过期!" };

            var userItem = _rep.FirstOrDefault<YscUser>(p => p.Status == 0 && p.Id == model.Id);
            if (userItem == null)
                return new ReturnValueModel { Code = 404, Msg = "该用户状态异常!" };

            userItem.UserName = !string.IsNullOrEmpty(model.UserName) ? model.UserName : userItem.UserName;
            userItem.AreaUnCode = !string.IsNullOrEmpty(model.AreaUnCode) ? model.AreaUnCode : userItem.AreaUnCode;
            userItem.Introduce = !string.IsNullOrEmpty(model.Introduce) ? model.Introduce : userItem.Introduce;
            userItem.Age = model.Age;
            userItem.Sex = model.Sex;

            _rep.Update(userItem);

            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }

        /// <summary>
        /// 用户媒体信息更新
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnValueModel UpdateUserMedia(YscUserMediaModel model)
        {
            if (string.IsNullOrEmpty(model.Id))
                return new ReturnValueModel { Code = 401, Msg = "临时凭证已过期!" };

            var userItem = _rep.FirstOrDefault<YscUser>(p => p.Status == 0 && p.Id == model.Id);
            if (userItem == null)
                return new ReturnValueModel { Code = 404, Msg = "该用户状态异常!" };

            userItem.HeadPortraitUrl = !string.IsNullOrEmpty(model.HeadPortraitUrl) ? model.HeadPortraitUrl : userItem.HeadPortraitUrl;
            userItem.Background = !string.IsNullOrEmpty(model.Background) ? model.Background : userItem.Background;

            _rep.Update(userItem);

            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }

        /// <summary>
        /// 用户历史报价
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public ReturnValueModel GetUserHistoryPriceAll(int index, int size, string userId, string dateTime)
        {
            if (string.IsNullOrEmpty(userId))
                return new ReturnValueModel { Code = 401, Msg = "临时凭证已过期!" };

            var userItem = _rep.FirstOrDefault<YscUser>(p => p.Status == 0 && p.Id == userId);
            if (userItem == null)
                return new ReturnValueModel { Code = 404, Msg = "该用户状态异常!" };


            #region 非认证用户

            if (userItem.IsAttest == false)
            {
                var fishAllD = _rep.Where<FishSpecies>(p => p.Status == 0).ToList();

                var marketPriceHistoryListD = from a in _rep.Where<PlaceOfOriginPrice>(p => p.Status == 0 && p.UserId == userId)
                                              join m in _rep.Where<PlaceOfOriginUnit>(p => p.Status == 0) on a.PlaceOfOriginId equals m.Id
                                              join f in _rep.Where<FishSpecies>(p => p.Status == 0) on a.FishId.Trim() equals f.FishCode.Trim()
                                              select new
                                              {
                                                  a.PlaceOfOriginPricesModel,
                                                  a.Id,
                                                  a.FishId,
                                                  f.FishName,
                                                  a.UserId,
                                                  a.AveragePrice,
                                                  MarketId = m.Id,
                                                  UnitAddress = m.Address,
                                                  m.PlaceOriginName,
                                                  a.CreateTime
                                              };

                var listD = marketPriceHistoryListD
                     .WhereIf(p => UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day") == UtilsHelp.Condition(Convert.ToDateTime(dateTime), "Day"), string.IsNullOrEmpty(dateTime) == false);

                var marketPriceHistoryAllD = listD.OrderByDescending(p => p.CreateTime)
                    .ToPaginationList(index, size)
                    .ToList()
                     .Select(p => new MarketPriceModel
                     {
                         Id = p.Id,
                         FishId = p.FishId,
                         FishName = p.FishName,
                         UserId = p.UserId,
                         MarketId = p.MarketId,
                         MarketName = p.PlaceOriginName,
                         UnitAddress = p.UnitAddress,
                         AveragePrice = p.AveragePrice,
                         CreateTime = p.CreateTime,
                         MarketPricesModel = p.PlaceOfOriginPricesModel.Join(fishAllD, a => a.DescriptionId.Trim(), f => f.FishCode, (a, f) => new MarketPricesModel { DescriptionId = a.DescriptionId.Trim(), Description = f.Description.Trim(), Price = a.Price, FishName = f.FishName }).ToList()
                         //  .Join(fishAll.Where(a => a.Status == 0), a => a.FishName, f => f.FishName, (a, f) => new MarketPricesModel { DescriptionId = a.DescriptionId.Trim(), Description = f.Description.Trim(), Price = a.Price }).ToList(),
                     }).ToList();

                foreach (var item in marketPriceHistoryAllD)
                {
                    var DescriptionlistD = fishAllD.Where(p => p.FishName == item.FishName).ToList().Select(p => new MarketPricesModel
                    {
                        DescriptionId = p.FishCode,
                        Description = p.Description.Trim(),
                        Price = 0
                    }).ToList();
                    foreach (var pricesItemD in DescriptionlistD)
                    {
                        if (item.MarketPricesModel.Where(p => p.Description == pricesItemD.Description).Count() == 0)
                            item.MarketPricesModel.Add(pricesItemD);
                    }

                }


                var marketModelsD = marketPriceHistoryAllD
                     .GroupBy(p => new
                     {
                         p.MarketName,
                         Day = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day")
                     })
                     .Select(p => new PriceRecordModel
                     {
                         Day = p.Key.Day,
                         MarketName = p.Key.MarketName,
                         HistoryDate = p.ToList()
                     });

                var fishAllF = _rep.Where<FishSpecies>(p => p.Status == 0).ToList();

                var marketPriceHistoryListF = from a in _rep.Where<MarketPrice>(p => p.Status == 0 && p.UserId == userId)
                                              join m in _rep.Where<MarketUnit>(p => p.Status == 0) on a.MarketId equals m.Id
                                              join f in _rep.Where<FishSpecies>(p => p.Status == 0) on a.FishId.Trim() equals f.FishCode
                                              select new
                                              {
                                                  a.MarketPrices,
                                                  a.Id,
                                                  a.FishId,
                                                  f.FishName,
                                                  a.UserId,
                                                  a.AveragePrice,
                                                  MarketId = m.Id,
                                                  UnitAddress = m.Address,
                                                  m.MarketName,
                                                  a.CreateTime
                                              };

                var listF = marketPriceHistoryListF
                     .WhereIf(p => UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day") == UtilsHelp.Condition(Convert.ToDateTime(dateTime), "Day"), string.IsNullOrEmpty(dateTime) == false);

                var marketPriceHistoryAllF = listF.OrderByDescending(p => p.CreateTime)
                    .ToPaginationList(index, size)
                    .ToList()
                     .Select(p => new MarketPriceModel
                     {
                         Id = p.Id,
                         FishId = p.FishId,
                         FishName = p.FishName,
                         UserId = p.UserId,
                         MarketId = p.MarketId,
                         MarketName = p.MarketName,
                         UnitAddress = p.UnitAddress,
                         AveragePrice = p.AveragePrice,
                         CreateTime = p.CreateTime,
                         MarketPricesModel = p.MarketPrices.Join(fishAllF, a => a.DescriptionId.Trim(), f => f.FishCode, (a, f) => new MarketPricesModel { DescriptionId = a.DescriptionId.Trim(), Description = f.Description.Trim(), Price = a.Price, FishName = f.FishName }).ToList()
                         //  .Join(fishAll.Where(a => a.Status == 0), a => a.FishName, f => f.FishName, (a, f) => new MarketPricesModel { DescriptionId = a.DescriptionId.Trim(), Description = f.Description.Trim(), Price = a.Price }).ToList(),
                     }).ToList();

                foreach (var item in marketPriceHistoryAllF)
                {
                    var DescriptionlistF = fishAllF.Where(p => p.FishName == item.FishName).ToList().Select(p => new MarketPricesModel
                    {
                        DescriptionId = p.FishCode,
                        Description = p.Description.Trim(),
                        Price = 0
                    }).ToList();
                    foreach (var pricesItem in DescriptionlistF)
                    {
                        if (item.MarketPricesModel.Where(p => p.Description == pricesItem.Description).Count() == 0)
                            item.MarketPricesModel.Add(pricesItem);
                    }
                }


                var marketModelsF = marketPriceHistoryAllF
                     .GroupBy(p => new
                     {
                         p.MarketName,
                         Day = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day")
                     })
                     .Select(p => new PriceRecordModel
                     {
                         Day = p.Key.Day,
                         MarketName = p.Key.MarketName,
                         HistoryDate = p.ToList()
                     });

                var models = new List<PriceRecordModel>();

                foreach (var item in marketModelsD.ToList())
                {
                    item.UnintType = 1;
                    models.Add(item);
                }
                foreach (var item in marketModelsF.ToList())
                {

                    item.UnintType = 0;
                    models.Add(item);
                }

                return new ReturnValueModel { Code = 200, Msg = "success!", Result = new { Data = models } };

            }

            #endregion


            //if (userItem.IsAttest == false)
            //    return new ReturnValueModel { Code = 401, Msg = "权限不足，请前往认证!" };
            var dictionaryAll = _rep.FirstOrDefault<Dictionary>(p => p.Id == userItem.AttestType);

            if (dictionaryAll.Name == "产地报价员")
            {
                var fishAllC = _rep.Where<FishSpecies>(p => p.Status == 0).ToList();

                var marketPriceHistoryListC = from a in _rep.Where<PlaceOfOriginPrice>(p => p.Status == 0 && p.UserId == userId)
                                              join m in _rep.Where<PlaceOfOriginUnit>(p => p.Status == 0) on a.PlaceOfOriginId equals m.Id
                                              join f in _rep.Where<FishSpecies>(p => p.Status == 0) on a.FishId.Trim() equals f.FishCode
                                              select new
                                              {
                                                  a.PlaceOfOriginPricesModel,
                                                  a.Id,
                                                  a.FishId,
                                                  f.FishName,
                                                  a.UserId,
                                                  a.AveragePrice,
                                                  MarketId = m.Id,
                                                  UnitAddress = m.Address,
                                                  m.PlaceOriginName,
                                                  a.CreateTime
                                              };

                var listC = marketPriceHistoryListC
                     .WhereIf(p => UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day") == UtilsHelp.Condition(Convert.ToDateTime(dateTime), "Day"), string.IsNullOrEmpty(dateTime) == false);

                var marketPriceHistoryAllC = listC.OrderByDescending(p => p.CreateTime)
                    .ToPaginationList(index, size)
                    .ToList()
                     .Select(p => new MarketPriceModel
                     {
                         Id = p.Id,
                         FishId = p.FishId,
                         FishName = p.FishName,
                         UserId = p.UserId,
                         MarketId = p.MarketId,
                         MarketName = p.PlaceOriginName,
                         UnitAddress = p.UnitAddress,
                         AveragePrice = p.AveragePrice,
                         CreateTime = p.CreateTime,
                         MarketPricesModel = p.PlaceOfOriginPricesModel.Join(fishAllC, a => a.DescriptionId.Trim(), f => f.FishCode, (a, f) => new MarketPricesModel { DescriptionId = a.DescriptionId.Trim(), Description = f.Description.Trim(), Price = a.Price, FishName = f.FishName }).ToList()
                         //  .Join(fishAll.Where(a => a.Status == 0), a => a.FishName, f => f.FishName, (a, f) => new MarketPricesModel { DescriptionId = a.DescriptionId.Trim(), Description = f.Description.Trim(), Price = a.Price }).ToList(),
                     }).ToList();

                foreach (var item in marketPriceHistoryAllC)
                {
                    var DescriptionlistC = fishAllC.Where(p => p.FishName == item.FishName).ToList().Select(p => new MarketPricesModel
                    {
                        DescriptionId = p.FishCode,
                        Description = p.Description.Trim(),
                        Price = 0
                    }).ToList();
                    foreach (var pricesItemC in DescriptionlistC)
                    {
                        if (item.MarketPricesModel.Where(p => p.Description == pricesItemC.Description).Count() == 0)
                            item.MarketPricesModel.Add(pricesItemC);
                    }

                }


                var marketModelsC = marketPriceHistoryAllC
                     .GroupBy(p => new
                     {
                         p.MarketName,
                         Day = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day")
                     })
                     .Select(p => new
                     {
                         p.Key.Day,
                         p.Key.MarketName,
                         HistoryDate = p
                     });
                return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Data = marketModelsC } };
            }


            var fishAll = _rep.Where<FishSpecies>(p => p.Status == 0).ToList();

            var marketPriceHistoryList = from a in _rep.Where<MarketPrice>(p => p.Status == 0 && p.UserId == userId)
                                         join m in _rep.Where<MarketUnit>(p => p.Status == 0) on a.MarketId equals m.Id
                                         join f in _rep.Where<FishSpecies>(p => p.Status == 0) on a.FishId.Trim() equals f.FishCode
                                         select new
                                         {
                                             a.MarketPrices,
                                             a.Id,
                                             a.FishId,
                                             f.FishName,
                                             a.UserId,
                                             a.AveragePrice,
                                             MarketId = m.Id,
                                             UnitAddress = m.Address,
                                             m.MarketName,
                                             a.CreateTime
                                         };

            var list = marketPriceHistoryList
                 .WhereIf(p => UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day") == UtilsHelp.Condition(Convert.ToDateTime(dateTime), "Day"), string.IsNullOrEmpty(dateTime) == false);

            var marketPriceHistoryAll = list.OrderByDescending(p => p.CreateTime)
                .ToPaginationList(index, size)
                .ToList()
                 .Select(p => new MarketPriceModel
                 {
                     Id = p.Id,
                     FishId = p.FishId,
                     FishName = p.FishName,
                     UserId = p.UserId,
                     MarketId = p.MarketId,
                     MarketName = p.MarketName,
                     UnitAddress = p.UnitAddress,
                     AveragePrice = p.AveragePrice,
                     CreateTime = p.CreateTime,
                     MarketPricesModel = p.MarketPrices.Join(fishAll, a => a.DescriptionId.Trim(), f => f.FishCode, (a, f) => new MarketPricesModel { DescriptionId = a.DescriptionId.Trim(), Description = f.Description.Trim(), Price = a.Price, FishName = f.FishName }).ToList()
                     //  .Join(fishAll.Where(a => a.Status == 0), a => a.FishName, f => f.FishName, (a, f) => new MarketPricesModel { DescriptionId = a.DescriptionId.Trim(), Description = f.Description.Trim(), Price = a.Price }).ToList(),
                 }).ToList();

            foreach (var item in marketPriceHistoryAll)
            {
                var Descriptionlist = fishAll.Where(p => p.FishName == item.FishName).ToList().Select(p => new MarketPricesModel
                {
                    DescriptionId = p.FishCode,
                    Description = p.Description.Trim(),
                    Price = 0
                }).ToList();
                foreach (var pricesItem in Descriptionlist)
                {
                    if (item.MarketPricesModel.Where(p => p.Description == pricesItem.Description).Count() == 0)
                        item.MarketPricesModel.Add(pricesItem);
                }

            }


            var marketModels = marketPriceHistoryAll
                 .GroupBy(p => new
                 {
                     p.MarketName,
                     Day = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day")
                 })
                 .Select(p => new
                 {
                     p.Key.Day,
                     p.Key.MarketName,
                     HistoryDate = p
                 });
            return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Data = marketModels } };
        }

        /// <summary>
        /// 用户认证
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnValueModel AddUserAttest(UserAttestModel model)
        {
            if (string.IsNullOrEmpty(model.UserId))
                return new ReturnValueModel { Code = 401, Msg = "临时凭证已过期!" };

            var userItem = _rep.FirstOrDefault<YscUser>(p => p.Status == 0 && p.Id == model.UserId);
            if (userItem == null)
                return new ReturnValueModel { Code = 404, Msg = "该用户状态异常!" };

            if (userItem.IsAttest == true)
                return new ReturnValueModel { Code = 400, Msg = "用户已认证!" };

            var userAttestAll = _rep.Where<UserAttest>(p => p.UserId == model.UserId).ToList();
            if (userAttestAll.Count() > 0)
                return new ReturnValueModel { Code = 400, Msg = "认证申请已提交,请耐心等待工作人员审核!" };


            UserAttest userAttest = new UserAttest()
            {
                Id = Guid.NewGuid().ToString(),
                Status = 0,
                CreateTime = DateTime.Now,
                CreateId = model.UserId,
                UserId = model.UserId,
                AttestType = model.AttestType,
                ContactsName = model.ContactsName,
                ContactsPhone = model.ContactsPhone,
            };

            List<UserAttestUnit> userAttestUnitList = new List<UserAttestUnit>();

            foreach (var item in model.UserAttestUnitAll)
            {
                UserAttestUnit items = new UserAttestUnit()
                {
                    Id = Guid.NewGuid().ToString(),
                    UserAttestId = userAttest.Id,
                    UnitName = item.UnitName,
                    Address = item.Address,
                    UnCode = item.UnCode,
                    Remarks = item.Remarks,
                    Status = 0,
                    CreateId = model.UserId,
                    CreateTime = DateTime.Now
                };
                userAttestUnitList.Add(items);


            }
            userAttest.UserAttestUnitAll = userAttestUnitList;
            try
            {
                _rep.Insert(userAttest);

                if (!string.IsNullOrEmpty(model.Url))
                {
                    MediaImage image = new MediaImage()
                    {
                        Id = Guid.NewGuid().ToString(),
                        BllId = userAttest.Id,
                        BllType = "用户认证",
                        FileUrl = model.Url,
                        Author = userItem.UserName,
                        Type = "图片",
                        Status = 0,
                        CreateTime = DateTime.Now,
                        CreateId = model.UserId
                    };
                    _rep.Insert(image);
                }
            }
            catch
            {
                _rep.Remove(userAttest);
                return new ReturnValueModel { Code = 500, Msg = "Internal Server Error!" };
            }
            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }

        /// <summary>
        /// 验证码验证
        /// </summary>
        /// <param name="smsCode"></param>
        /// <param name="phone"></param>
        /// <returns></returns>
        public ReturnValueModel SMSVerification(string smsCode, string phone)
        {
            var userItem = _rep.Where<YscUser>(p => p.Status == 0 && p.Phone == phone).ToList();

            if (userItem.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "用户不存在!", };

            var msmAll = _rep.Where<MSM>(p => p.Status == 0 && p.phone == phone && (DateTime.Now - p.CreateTime).Minutes <= 15).ToList();

            //  var erfgf = (DateTime.Now - msmAll.FirstOrDefault().CreateTime).Minutes;
            if (msmAll.Count() == 0)
                return new ReturnValueModel { Code = 400, Msg = "验证码已过期,请重新发送验证码!", };

            if (msmAll.FirstOrDefault().VerificationCode.ToString() != smsCode)
                return new ReturnValueModel { Code = 400, Msg = "验证码错误,请重新发送验证码!", };

            _rep.RemoveRange(msmAll);

            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }

        /// <summary>
        /// 用户密码修改
        /// </summary>
        /// <param name="smsCode"></param>
        /// <param name="Password"></param>
        /// <returns></returns>
        public ReturnValueModel UpdateUserPassword(string phone, string Password)
        {
            var userItem = _rep.Where<YscUser>(p => p.Status == 0 && p.Phone == phone).ToList();

            if (string.IsNullOrEmpty(Password))
                return new ReturnValueModel { Code = 400, Msg = "密码输入错误!", };

            if (userItem.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "用户不存在!", };

            var user = userItem.FirstOrDefault();

            user.Password = UtilsHelp.GetMD5(Password);

            _rep.Update(user);
            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }

        public ReturnValueModel WXLogin(string encryptedDataStr, string key, string iv)
        {
            string CodeUrl = "https://api.weixin.qq.com/sns/jscode2session?";
            string getStr = CodeUrl + string.Format("appid=wxedf019d52016cee6&&secret=a5ed0c47535ae7cf20891543deee32f0&&grant_type=authorization_code&&js_code={0}", key);
            var code = HttpUtils.HttpGetRequest(getStr);
            WXCode wxCode = JsonConvert.DeserializeObject<WXCode>(code);

            var result = AesHelper.DecryptForWeChatApplet(encryptedDataStr, wxCode.session_key, iv);
            YscUserWXModel wxModel = JsonConvert.DeserializeObject<YscUserWXModel>(result);

            var userAll = _rep.Where<YscUser>(p => p.OpenId == wxModel.openId).ToList();
            if (userAll.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "success!", Result = new { OpenId = wxModel.openId } };

            string TokenUrl = "http://yscoauth.cnfm.com.cn:8099/connect/token";
            //string TokenUrl = "http://localhost:5000/connect/token";
            Dictionary<string, string> postData = new Dictionary<string, string>();
            postData.Add("userName", userAll.FirstOrDefault().Phone);
            postData.Add("password", userAll.FirstOrDefault().Password);
            postData.Add("client_id", "ro.client");
            postData.Add("client_secret", "secret");
            postData.Add("grant_type", "password");

            var userName = userAll.FirstOrDefault();

            // 自己实现的http请求
            string postStrs = HttpUtils.DictoryToGetParam(postData);
            var reposes = HttpUtils.HttpPostRequest(TokenUrl, postStrs);
            if (reposes.Contains("400"))
                return new ReturnValueModel { Code = 400, Msg = "请求错误!", Result = reposes };
            TokenModel tokenModels = JsonConvert.DeserializeObject<TokenModel>(reposes);
            tokenModels.UserName = System.Web.HttpUtility.UrlDecode(userName.UserName, System.Text.Encoding.UTF8);
            tokenModels.UserHeadPortraitUrl = userName.HeadPortraitImageUrl;
            if (userAll.FirstOrDefault().IsAttest == true && string.IsNullOrEmpty(userAll.FirstOrDefault().AttestType))
                return new ReturnValueModel { Code = 500, Msg = "用户权限丢失!" };
            if (userAll.FirstOrDefault().IsAttest == true)
                tokenModels.AttestName = _rep.FirstOrDefault<Dictionary>(p => p.Id == userAll.FirstOrDefault().AttestType).Name;

            return new ReturnValueModel { Code = 200, Msg = "success!", Result = tokenModels };
        }

        public ReturnValueModel WXRegistered(WXRegisteredModel model)
        {
            var item = _rep.FirstOrDefault<YscUser>(p => p.Phone == model.Phone);
            if (item != null)
                return new ReturnValueModel { Code = 400, Msg = "您已注册，请前往登陆!", };

            var msmAll = _rep.Where<MSM>(p => p.Status == 0 && p.phone == model.Phone && (DateTime.Now - p.CreateTime).Minutes <= 15).ToList();
            if (msmAll.Count() == 0)
                return new ReturnValueModel { Code = 400, Msg = "验证码已过期,请重新发送验证码!", };

            if (msmAll.FirstOrDefault().VerificationCode.ToString() != model.SMSCode)
                return new ReturnValueModel { Code = 400, Msg = "验证码错误,请重新发送验证码!", };


            YscUser yscUser = new YscUser()
            {
                Id = Guid.NewGuid().ToString(),
                UserName = System.Web.HttpUtility.UrlEncode(model.UserName, System.Text.Encoding.UTF8),
                Password = string.IsNullOrEmpty(model.PassWord) ? UtilsHelp.GetMD5("123456") : UtilsHelp.GetMD5(model.PassWord),
                Phone = model.Phone,
                OpenId = model.OpenId,
                HeadPortraitUrl = model.HeadPortraitUrl,
                Age = DateTime.Now,
                AreaUnCode = "802",
                Sex = 0,
                IsAttest = false,
                Status = 0,
                CreateTime = DateTime.Now,
                CreateId = "4076e59b-c219-11e9-a7b7-48d53943449f",
            };
            _rep.Insert(yscUser);

            string TokenUrl = "http://yscoauth.cnfm.com.cn:8099/connect/token";
            //string TokenUrl = "http://localhost:5000/connect/token";
            Dictionary<string, string> postData = new Dictionary<string, string>();
            postData.Add("userName", yscUser.Phone);
            postData.Add("password", yscUser.Password);
            postData.Add("client_id", "ro.client");
            postData.Add("client_secret", "secret");
            postData.Add("grant_type", "password");

            // 自己实现的http请求
            string postStrs = HttpUtils.DictoryToGetParam(postData);
            var reposes = HttpUtils.HttpPostRequest(TokenUrl, postStrs);
            if (reposes.Contains("400"))
                return new ReturnValueModel { Code = 400, Msg = "请求错误!", Result = reposes };
            TokenModel tokenModels = JsonConvert.DeserializeObject<TokenModel>(reposes);
            tokenModels.UserName = System.Web.HttpUtility.UrlDecode(yscUser.UserName, System.Text.Encoding.UTF8);
            tokenModels.UserHeadPortraitUrl = yscUser.HeadPortraitImageUrl;
            // tokenModels.IsAttest = yscUser.IsAttest;

            var msmlist = _rep.Where<MSM>(p => p.phone == model.Phone && (DateTime.Now - p.CreateTime).Minutes > 15).ToList();
            if (msmlist.Count() > 0)
                _rep.RemoveRange(msmlist);
            return new ReturnValueModel { Code = 200, Msg = "success!", Result = tokenModels };
        }

        public ReturnValueModel GetUserHistoryPriceYKAll(int index, int size, string userId, string dateTime)
        {
            if (string.IsNullOrEmpty(userId))
                return new ReturnValueModel { Code = 401, Msg = "临时凭证已过期!" };

            var userItem = _rep.FirstOrDefault<YscUser>(p => p.Status == 0 && p.Id == userId);
            if (userItem == null)
                return new ReturnValueModel { Code = 404, Msg = "该用户状态异常!" };


            var fishAllC = _rep.Where<FishSpecies>(p => p.Status == 0).ToList();

            var marketPriceHistoryListC = from a in _rep.Where<PlaceOfOriginPrice>(p => p.Status == 0 && p.UserId == userId)
                                          join m in _rep.Where<PlaceOfOriginUnit>(p => p.Status == 0) on a.PlaceOfOriginId equals m.Id
                                          join f in _rep.Where<FishSpecies>(p => p.Status == 0) on a.FishId.Trim() equals f.FishCode
                                          select new
                                          {
                                              a.PlaceOfOriginPricesModel,
                                              a.Id,
                                              a.FishId,
                                              f.FishName,
                                              a.UserId,
                                              a.AveragePrice,
                                              MarketId = m.Id,
                                              UnitAddress = m.Address,
                                              m.PlaceOriginName,
                                              a.CreateTime
                                          };

            var listC = marketPriceHistoryListC
                 .WhereIf(p => UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day") == UtilsHelp.Condition(Convert.ToDateTime(dateTime), "Day"), string.IsNullOrEmpty(dateTime) == false);

            var marketPriceHistoryAllC = listC.OrderByDescending(p => p.CreateTime)
                .ToPaginationList(index, size)
                .ToList()
                 .Select(p => new MarketPriceModel
                 {
                     Id = p.Id,
                     FishId = p.FishId,
                     FishName = p.FishName,
                     UserId = p.UserId,
                     MarketId = p.MarketId,
                     MarketName = p.PlaceOriginName,
                     UnitAddress = p.UnitAddress,
                     AveragePrice = p.AveragePrice,
                     CreateTime = p.CreateTime,
                     MarketPricesModel = p.PlaceOfOriginPricesModel.Join(fishAllC, a => a.DescriptionId.Trim(), f => f.FishCode, (a, f) => new MarketPricesModel { DescriptionId = a.DescriptionId.Trim(), Description = f.Description.Trim(), Price = a.Price, FishName = f.FishName }).ToList()
                     //  .Join(fishAll.Where(a => a.Status == 0), a => a.FishName, f => f.FishName, (a, f) => new MarketPricesModel { DescriptionId = a.DescriptionId.Trim(), Description = f.Description.Trim(), Price = a.Price }).ToList(),
                 }).ToList();

            foreach (var item in marketPriceHistoryAllC)
            {
                var DescriptionlistC = fishAllC.Where(p => p.FishName == item.FishName).ToList().Select(p => new MarketPricesModel
                {
                    DescriptionId = p.FishCode,
                    Description = p.Description.Trim(),
                    Price = 0
                }).ToList();
                foreach (var pricesItemC in DescriptionlistC)
                {
                    if (item.MarketPricesModel.Where(p => p.Description == pricesItemC.Description).Count() == 0)
                        item.MarketPricesModel.Add(pricesItemC);
                }

            }


            var marketModelsC = marketPriceHistoryAllC
                 .GroupBy(p => new
                 {
                     p.MarketName,
                     Day = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day")
                 })
                 .Select(p => new
                 {
                     p.Key.Day,
                     p.Key.MarketName,
                     HistoryDate = p
                 });

            var fishAll = _rep.Where<FishSpecies>(p => p.Status == 0).ToList();

            var marketPriceHistoryList = from a in _rep.Where<MarketPrice>(p => p.Status == 0 && p.UserId == userId)
                                         join m in _rep.Where<MarketUnit>(p => p.Status == 0) on a.MarketId equals m.Id
                                         join f in _rep.Where<FishSpecies>(p => p.Status == 0) on a.FishId.Trim() equals f.FishCode
                                         select new
                                         {
                                             a.MarketPrices,
                                             a.Id,
                                             a.FishId,
                                             f.FishName,
                                             a.UserId,
                                             a.AveragePrice,
                                             MarketId = m.Id,
                                             UnitAddress = m.Address,
                                             m.MarketName,
                                             a.CreateTime
                                         };

            var list = marketPriceHistoryList
                 .WhereIf(p => UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day") == UtilsHelp.Condition(Convert.ToDateTime(dateTime), "Day"), string.IsNullOrEmpty(dateTime) == false);

            var marketPriceHistoryAll = list.OrderByDescending(p => p.CreateTime)
                .ToPaginationList(index, size)
                .ToList()
                 .Select(p => new MarketPriceModel
                 {
                     Id = p.Id,
                     FishId = p.FishId,
                     FishName = p.FishName,
                     UserId = p.UserId,
                     MarketId = p.MarketId,
                     MarketName = p.MarketName,
                     UnitAddress = p.UnitAddress,
                     AveragePrice = p.AveragePrice,
                     CreateTime = p.CreateTime,
                     MarketPricesModel = p.MarketPrices.Join(fishAll, a => a.DescriptionId.Trim(), f => f.FishCode, (a, f) => new MarketPricesModel { DescriptionId = a.DescriptionId.Trim(), Description = f.Description.Trim(), Price = a.Price, FishName = f.FishName }).ToList()
                     //  .Join(fishAll.Where(a => a.Status == 0), a => a.FishName, f => f.FishName, (a, f) => new MarketPricesModel { DescriptionId = a.DescriptionId.Trim(), Description = f.Description.Trim(), Price = a.Price }).ToList(),
                 }).ToList();

            foreach (var item in marketPriceHistoryAll)
            {
                var Descriptionlist = fishAll.Where(p => p.FishName == item.FishName).ToList().Select(p => new MarketPricesModel
                {
                    DescriptionId = p.FishCode,
                    Description = p.Description.Trim(),
                    Price = 0
                }).ToList();
                foreach (var pricesItem in Descriptionlist)
                {
                    if (item.MarketPricesModel.Where(p => p.Description == pricesItem.Description).Count() == 0)
                        item.MarketPricesModel.Add(pricesItem);
                }

            }


            var marketModels = marketPriceHistoryAll
                 .GroupBy(p => new
                 {
                     p.MarketName,
                     Day = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day")
                 })
                 .Select(p => new
                 {
                     p.Key.Day,
                     p.Key.MarketName,
                     HistoryDate = p
                 });

            foreach (var item in marketModelsC.ToList())
            {
                marketModels.ToList().Add(item);
            }


            return new ReturnValueModel { Code = 200, Msg = "success!", Result = marketModels };
        }
    }
}